---
title: Avatar
description: Using the avatar machine in your project.
package: "@zag-js/avatar"
---

The Avatar component is a React component that represents a user avatar or
profile picture. It displays an image or initials within container.

Avatar provides support for fallback text or elements when the image fails to
load, or when the image is not provided.

<Resources pkg="@zag-js/avatar" />

<Showcase id="Avatar" />

## Installation

To use the avatar machine in your project, run the following command in your
command line:

<CodeSnippet id="avatar/installation.mdx" />

## Anatomy

To set up the avatar correctly, you'll need to understand its anatomy and how we
name its parts.

> Each part includes a `data-part` attribute to help identify them in the DOM.

<Anatomy id="avatar" />

## Usage

First, import the avatar package into your project

```jsx
import * as avatar from "@zag-js/avatar"
```

The avatar package exports two key functions:

- `machine` — The state machine logic for the avatar widget.
- `connect` — The function that translates the machine's state to JSX attributes
  and event handlers.

> You'll also need to provide a unique `id` to the `useMachine` hook. This is
> used to ensure that every part has a unique identifier.

Next, import the required hooks and functions for your framework and use the
avatar machine in your project 🔥

<CodeSnippet id="avatar/usage.mdx" />

### Listening for loading status changes

When the image has loaded or failed to load, the `onStatusChange` callback is
invoked.

```jsx {2}
const service = useMachine(avatar.machine, {
  onStatusChange(details) {
    // details => { status: "error" | "loaded" }
  },
})
```

## Styling guide

Earlier, we mentioned that each avatar part has a `data-part` attribute added to
them to select and style them in the DOM.

```css
[data-scope="avatar"][data-part="root"] {
  /* Styles for the root part */
}

[data-scope="avatar"][data-part="image"] {
  /* Styles for the image part */
}

[data-scope="avatar"][data-part="fallback"] {
  /* Styles for the fallback part */
}
```

## Creating Component

Create your avatar component by abstracting the machine into your own component.

### Usage

<CodeSnippet id="avatar/component.usage.mdx" />

### Implementation

Use the the `splitProps` utility to separate the machine's props from the
component's props.

<CodeSnippet id="avatar/component.api.mdx" />

## Methods and Properties

### Machine Context

The avatar machine exposes the following context properties:

<ContextTable name="avatar" />

### Machine API

The avatar `api` exposes the following methods:

<ApiTable name="avatar" />

### Data Attributes

<DataAttrTable name="avatar" />
